package juhouse.glb.content.action;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import juhouse.framework.tools.DoDate;
import juhouse.framework.tools.WaterMark;
import juhouse.glb.content.form.ContentUploadForm;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class ContentUploadAction extends DispatchAction{

    public ActionForward contentUpload(ActionMapping mapping,
    		ActionForm form, HttpServletRequest request,
    		HttpServletResponse response) throws Exception {
    	
    	ContentUploadForm contentUploadForm = (ContentUploadForm) form;
    	int waterMark = contentUploadForm.getWaterMark();
    	WaterMark myWaterMark = new WaterMark();
    	String FileExt="",newFileName="",RealPath,FilePath;
    	RealPath=this.getServlet().getServletContext().getRealPath("/");
    	DoDate myDoDate = new DoDate();
    	String currentlyDate = myDoDate.formatDate(myDoDate.currentlyTime(),"yyyy-MM-dd");
    	FilePath = "content/contentPhoto/"+currentlyDate+"/";
    	File dir = new File(RealPath+FilePath);
    	if(!dir.exists()) dir.mkdir();
		String contentType = contentUploadForm.getPic().getContentType();
		if(contentType.equals("image/gif")||contentType.equals("image/jpg")||contentType.equals("image/jpeg")||contentType.equals("image/pjpeg"))
		{
	    	if (contentUploadForm.getPic().getFileSize()>0&&contentUploadForm.getPic().getFileSize()<1024*500)
	    	{
	    		String[] FileName = contentUploadForm.getPic().getFileName().split("\\.");
	    		FileExt=FileName[FileName.length-1].toLowerCase();
	    		newFileName = myDoDate.picTime()+"."+ FileExt;
	    		try{
	    			FileOutputStream fos = new FileOutputStream(RealPath+FilePath+newFileName);
	    			fos.write(contentUploadForm.getPic().getFileData());
	    			fos.close();
	     			if(waterMark==1)
	    			{
	    				myWaterMark.LetterWaterMark(RealPath+"images/letter.png",RealPath+FilePath+newFileName);
	    			}else if(waterMark==2){
	    				myWaterMark.ImgWaterMark(RealPath+"images/watermark.png",RealPath+FilePath+newFileName);
	    			}
	    		}catch(Exception e)
	    		{
	    			e.printStackTrace();
	    		}

	        	request.setAttribute("FileExt",FileExt);
	        	request.setAttribute("FileUrl",request.getContextPath()+"/"+FilePath+newFileName);
	        	return mapping.findForward("contentUploadSuccess");
	        	
	    	}else{
	    		return mapping.findForward("contentUploadDefeat");
	    	}
	    	
		}else{
			return mapping.findForward("contentUploadDefeat");
		}
    }
	
}
